import type { ReactNode } from 'react';
import React, { forwardRef, useCallback, useState } from 'react';
import SmartModal from '@/components/smartmodal';
import { MODAL_PADDING_HEIGHT, MODAL_HEADER_HEIGHT, MODAL_FOOTER_HEIGHT } from '@/utils/utils';
import type { BaseGridTransferProps } from './index';
import GridTransfer from './index';

export type modalProps = {
  title: ReactNode | string; // 弹窗标题
  visible: boolean; // modal是否可见
  onCancel?: Function; // modal取消按钮的回调
  onOk?: Function; // modal确认按钮的回调
  extraModalProps?: any; // 额外的modal的参数
};

export type GridTransferModalProps = modalProps & BaseGridTransferProps;

const DEFAULT_ANY_OBJECT: any = {};

/**
 * 表格穿梭框弹框组件
 */
export default forwardRef((props: GridTransferModalProps, ref: any) => {
  const {
    title,
    visible,
    onCancel,
    onOk,
    extraModalProps = DEFAULT_ANY_OBJECT,
    transKey,
    rowKey,
    schema,
    columns,
    left,
    right,
    dataSource,
    onSearch,
    targetKeys,
    onChange,
    onSortChange,
    ...res
  } = props;

  const [size, setSize] = useState({ width: 0, height: 0 });
  const { footer } = extraModalProps;

  const onModalSizeChange = useCallback(
    (width: number, height: number) => {
      setSize({
        width: width - 2 * MODAL_PADDING_HEIGHT,
        height: height - MODAL_HEADER_HEIGHT - 5 * MODAL_PADDING_HEIGHT - (footer === null ? 0 : MODAL_FOOTER_HEIGHT),
      });
    },
    [footer],
  );

  return (
    <SmartModal
      {...extraModalProps}
      id={transKey}
      title={title}
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
      onSizeChange={onModalSizeChange}
    >
      <GridTransfer
        ref={ref}
        transKey={transKey}
        rowKey={rowKey}
        schema={schema}
        columns={columns}
        left={left}
        right={right}
        dataSource={dataSource}
        height={size.height}
        width={size.width}
        onSearch={onSearch}
        targetKeys={targetKeys}
        onChange={onChange}
        onSortChange={onSortChange}
        {...res}
      />
    </SmartModal>
  );
});
